package com.hzcx.app.simplechat.ui.chat;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseFragment;
import com.hzcx.app.simplechat.bean.UpLoadImgBean;
import com.hzcx.app.simplechat.chat.ChatUi;
import com.hzcx.app.simplechat.chat.ChatUiHelper;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.chat.adapter.ChatBottomMenuAdapter;
import com.hzcx.app.simplechat.chat.bean.ChatMoreMenuBean;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.chat.interfaces.OnChatMessageListener;
import com.hzcx.app.simplechat.chat.ui.ChatMessageListView;
import com.hzcx.app.simplechat.chat.ui.RecordButton;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.event.ForwardEvent;
import com.hzcx.app.simplechat.event.ImageEvent;
import com.hzcx.app.simplechat.event.VideoEvent;
import com.hzcx.app.simplechat.event.VideoMessageEvent;
import com.hzcx.app.simplechat.ui.chat.adapter.ChatQuickMsgAdapter;
import com.hzcx.app.simplechat.ui.chat.bean.ChatBottomAssistantMenuBean;
import com.hzcx.app.simplechat.ui.chat.bean.ChatInfoAdapterBean;
import com.hzcx.app.simplechat.ui.chat.bean.ChatQuickMsgBean;
import com.hzcx.app.simplechat.ui.chat.contract.ChatContract;
import com.hzcx.app.simplechat.ui.chat.dialog.ChatShareUserDialog;
import com.hzcx.app.simplechat.ui.chat.event.ChatCollectEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatEmojiLikeEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatFriendDeleteEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatLocationEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatMessageListRefreshEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatQuickMsgRefreshEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatSearchMsgEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatShareUserEvent;
import com.hzcx.app.simplechat.ui.chat.presenter.ChatPresenter;
import com.hzcx.app.simplechat.ui.friend.bean.FriendBean;
import com.hzcx.app.simplechat.ui.friend.bean.FriendCityBean;
import com.hzcx.app.simplechat.ui.friend.event.AddFriendEvent;
import com.hzcx.app.simplechat.ui.group.LiveData.GroupInfoBeanLiveData;
import com.hzcx.app.simplechat.ui.group.bean.GroupInfoBean;
import com.hzcx.app.simplechat.ui.group.bean.MembersBean;
import com.hzcx.app.simplechat.ui.group.contract.GroupInfoContract;
import com.hzcx.app.simplechat.ui.home.AddFriendActivity;
import com.hzcx.app.simplechat.ui.home.HXGroupMessageListener;
import com.hzcx.app.simplechat.ui.home.HXGroupMessageRefreshInterface;
import com.hzcx.app.simplechat.ui.mine.MineUserInfoActivity;
import com.hzcx.app.simplechat.ui.publicui.CameraActivity;
import com.hzcx.app.simplechat.ui.publicui.CaptureResultActivity;
import com.hzcx.app.simplechat.ui.publicui.PublicRoundDialog;
import com.hzcx.app.simplechat.ui.publicui.VideoPalyActivity;
import com.hzcx.app.simplechat.ui.publicui.WebViewActivity;
import com.hzcx.app.simplechat.ui.publicui.bean.HxUserInfoBean;
import com.hzcx.app.simplechat.ui.publicui.interfaces.OnPublicMenuOnClickListener;
import com.hzcx.app.simplechat.ui.setting.FeedBackActivity;
import com.hzcx.app.simplechat.ui.user.UserInfoActivity;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.ui.user.event.UserRemarkEvent;
import com.hzcx.app.simplechat.util.AnimUtil;
import com.hzcx.app.simplechat.util.TextHttpUtil;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.app.AppHelper;
import com.hzcx.app.simplechat.util.badge.BadgeUtil;
import com.hzcx.app.simplechat.util.down.DownLoadUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.file.FileUtils;
import com.hzcx.app.simplechat.util.image.ImageUtil;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.photo.PhotoUtil;
import com.hzcx.app.simplechat.util.qrcode.QRCodeParseUtils;
import com.hzcx.app.simplechat.util.sp.SPUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;
import com.hzcx.app.simplechat.view.autogridview.PhotoLoader;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.zengyu.popupwindowlist.PopupWindowList;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.litepal.LitePal;
import org.litepal.crud.callback.FindMultiCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import indi.liyi.viewer.ImageViewer;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * 聊天界面fragment
 */
public class ChatFragment extends BaseFragment<ChatPresenter> implements BaseQuickAdapter.OnItemClickListener, OnResultCallbackListener<LocalMedia>,
        EMMessageListener, ChatContract.View, ChatUiHelper.OnChatUiHelperListener, OnChatMessageListener, GroupInfoContract.View, HXGroupMessageRefreshInterface {

    private static final int HANDLER_MESSAGE_REFRESH_LIST = 0;

    @BindView(R.id.include_emoji)
    LinearLayout includeEmoji;
    @BindView(R.id.include_menu)
    LinearLayout includeMenu;
    @BindView(R.id.include_quick_msg)
    LinearLayout includeQuickMsg;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.iv_voice)
    ImageView ivVoice;
    @BindView(R.id.iv_keyword)
    ImageView ivKeyword;
    @BindView(R.id.tv_voice)
    RecordButton tvVoice;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.iv_emoji)
    ImageView ivEmoji;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.tv_send)
    TextView tvSend;
    @BindView(R.id.home_emoji)
    LinearLayout homeEmoji;
    @BindView(R.id.rv_menu)
    RecyclerView rvMenu;
    @BindView(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    @BindView(R.id.main_layout)
    LinearLayout mainLayout;
    @BindView(R.id.chat_msg_listview)
    ChatMessageListView chatMsgListview;
    @BindView(R.id.rv_emoji_default)
    RecyclerView rvEmojiDefault;
    @BindView(R.id.rv_emoji_like)
    RecyclerView rvEmojiLike;
    @BindView(R.id.iv_emoji_default)
    ImageView ivEmojiDefault;
    @BindView(R.id.iv_emoji_like)
    ImageView ivEmojiLike;
    @BindView(R.id.imageViewer)
    ImageViewer imageViewer;
    @BindView(R.id.rv_quick_msg)
    RecyclerView rvQuickMsg;
    @BindView(R.id.ll_quick_msg_null)
    LinearLayout llQuickMsgNull;
    @BindView(R.id.rl_quick_msg_add)
    RelativeLayout rlQuickMsgAdd;
    @BindView(R.id.rl_quick_msg_manager)
    RelativeLayout rlQuickMsgManager;
    @BindView(R.id.rl_forward)
    RelativeLayout rlForward;
    @BindView(R.id.rl_down)
    RelativeLayout rlDown;
    @BindView(R.id.rl_delete)
    RelativeLayout rlDelete;
    @BindView(R.id.ll_select_more_bottom)
    LinearLayout llSelectMoreBottom;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.rl_collect)
    RelativeLayout rlCollect;
    @BindView(R.id.ll_custom_service)
    LinearLayout llCustomService;
    @BindView(R.id.iv_to_custom_service)
    ImageView ivToCustomService;
    @BindView(R.id.rl_menu_custom_service)
    RelativeLayout rlMenuCustomService;
    @BindView(R.id.tv_assistant_menu_one)
    TextView tvAssistantMenuOne;
    @BindView(R.id.tv_assistant_menu_two)
    TextView tvAssistantMenuTwo;
    @BindView(R.id.tv_online_state)
    TextView tvOnlineState;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.tv_noread_num)
    TextView tvNoreadNum;

    private List<ChatMoreMenuBean> menuList;
    private ChatBottomMenuAdapter menuAdapter;

    private EMConversation conversation;

    private String username;
    private int chatType; // 聊天类型，单聊还是群聊

    // 对方用户id
    private int receiveId;
    private String receiveName;
    private String receiveRemarkName;
    private String receiveHead;

    private int premisionTag; // 申请权限的TAG

    private HxUserInfoBean hxUserInfoBean;
    @Nullable
    private ChatInfoAdapterBean userInfoBean; // 对方的用户信息

    private ChatUiHelper mUiHelper;

    private List<ChatQuickMsgBean> quickMsgData; // 快捷回复列表
    private ChatQuickMsgAdapter quickMsgAdapter;

    private boolean isSecectMore; // 是否多选状态
    private List<Integer> selectMoreList; // 选择更多状态下，选中的列表
    private int forwardPos;// 选择转发的消息pos
    private boolean isItemForward = false; // 是否是消息列表单独转发
    private List<ChatBottomAssistantMenuBean> bottomAsistantMentList; // 底部菜单列表
    private String callPhone; // 要拨打的电话

    protected boolean hidden; // 当前界面是否隐藏

    @Override
    public int getLayout() {
        return R.layout.fragment_chat;
    }

    @Override
    public void initPresenter() {
        mPresenter = new ChatPresenter();
    }

    @Override
    public void initView() {
        selectMoreList = new ArrayList<>();

        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        hxUserInfoBean = (HxUserInfoBean) getArguments().getSerializable(ChatActivity.INTENT_HX_USER_INFO);

        imageViewer.imageLoader(new PhotoLoader());
    }

    @Override
    public void onResume() {
        super.onResume();

        // 初始化消息列表
        chatMsgListview.initEMConversation(username, chatType);

        if (chatType == ChatConstant.CHATTYPE_GROUP) {
            String groupID = String.valueOf(hxUserInfoBean.getMember_id());
            GroupInfoBean groupInfoBean = GroupInfoBeanLiveData.getGroupInfoBean(groupID);
            if (groupInfoBean != null) {
                userInfoBean = new ChatInfoAdapterBean(groupInfoBean);
                reStatus(groupInfoBean);
            } else {
                LitePal.where("group_id=?", groupID).findFirstAsync(GroupInfoBean.class).listen(groupInfo -> {
                    if (groupInfo != null) {
                        userInfoBean = new ChatInfoAdapterBean(groupInfo);
                        reStatus(groupInfo);
                    }
                });
            }
        }
    }

    private void reStatus(GroupInfoBean groupInfoBean) {
        if (groupInfoBean == null) {
            return;
        }
        tvTitle.post(() -> {
            userInfoBean = new ChatInfoAdapterBean(groupInfoBean);

            if (groupInfoBean.getMembers() != null) {
                tvTitle.setText(userInfoBean.groupInfoBean.getGroup_name() + "(" + groupInfoBean.getMember_total() + ")");
                Map<String, MembersBean> userInfoGroupMap = new HashMap<>();
                boolean inGroup = false;
                for (MembersBean bean: groupInfoBean.getMembers()) {
                    userInfoGroupMap.put(bean.getMember().getHxusername(), bean);
                }
//            if (userInfoGroupMap.get(UserInfoUtil.getUserXHId()) != null) {
                ivTitleRight.setVisibility(View.VISIBLE);
                ivTitleRight.setImageResource(R.mipmap.ic_icon_title_more);
//            } else {
//                ivTitleRight.setVisibility(View.GONE);
//            }
                chatMsgListview.updateMembers(userInfoGroupMap);
                chatMsgListview.refresh();
            } else {
                tvTitle.setText(userInfoBean.groupInfoBean.getGroup_name() + "(" + groupInfoBean.getMembersCount() + ")");
            }
        });

    }

    @Override
    public void initData() {

        try {
            // 拿到对方的聊天数据
            username = hxUserInfoBean.getHxusername();
            chatType = getArguments().getInt(ChatConstant.CHAT_MESSAGE_TYPE, ChatConstant.CHATTYPE_SINGLE);
            receiveId = hxUserInfoBean.getMember_id();
            receiveName = hxUserInfoBean.getNickname();
            receiveRemarkName = hxUserInfoBean.getRemarks_name();
            receiveHead = hxUserInfoBean.getAvatar();

            conversation = EMClient.getInstance().chatManager().getConversation(username, ChatUtil.getConversationType(chatType), true);
            // 设置所有消息已读
            conversation.markAllMessagesAsRead();

            ivTitleRight.setVisibility(View.VISIBLE);
            tvTitleRight.setVisibility(View.VISIBLE);

            // 重置桌面小红点数量
            int num = EMClient.getInstance().chatManager().getUnreadMessageCount();
            if (num > 0) {
                BadgeUtil.setBadgeCount(getActivity(), num, R.mipmap.ic_launcher);
            } else {
                BadgeUtil.resetBadgeCount(getActivity(), R.mipmap.ic_launcher);
            }

            initMenu();
            initChatUi();

            // 初始化消息列表
            chatMsgListview.initEMConversation(username, chatType);
            if (chatType == ChatConstant.CHATTYPE_GROUP) {
                String groupID = String.valueOf(hxUserInfoBean.getMember_id());
                GroupInfoBean groupInfoBean = GroupInfoBeanLiveData.getGroupInfoBean(groupID);
                if (groupInfoBean != null) {
                    userInfoBean = new ChatInfoAdapterBean(groupInfoBean);
                    reStatus(groupInfoBean);
                } else {
                    LitePal.where("group_id=?", groupID).findFirstAsync(GroupInfoBean.class).listen(groupInfo -> {
                        if (groupInfo != null) {
                            userInfoBean = new ChatInfoAdapterBean(groupInfo);
                            reStatus(groupInfo);
                        }
                    });
                }
            }

            // 新消息监听
            EMClient.getInstance().chatManager().addMessageListener(this);
            HXGroupMessageListener groupMessageListener = new HXGroupMessageListener();
            groupMessageListener.messageFragment = this;
            EMClient.getInstance().groupManager().addGroupChangeListener(groupMessageListener);

            // 获取对方的用户信息
            if (chatType == ChatConstant.CHATTYPE_SINGLE) {
                mPresenter.getUserInfo(getActivity(), receiveId, 0, false);
                if (EmptyUtils.isEmpty(hxUserInfoBean.getRemarks_name())) {
                    tvTitle.setText(hxUserInfoBean.getNickname());
                } else {
                    tvTitle.setText(hxUserInfoBean.getRemarks_name());
                }
            } else {
                mPresenter.getGroupInfo(getActivity(), String.valueOf(receiveId));
            }

            // 消息列表事件监听
            chatMsgListview.setOnChatMessageListener(this);
            chatMsgListview.setHxuserInfoBean(hxUserInfoBean);

            // 获取快捷回复数据
            mPresenter.getChatQuickMsgList(getActivity());

            // 快捷回复列表点击

            quickMsgAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    if (isDelete()) {
                        if (!isService()) {
                            ChatUtil.getInstance().insertDeleteMessage(conversation, username, receiveId,
                                    EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                            chatMsgListview.add();
                            return;
                        }
                    }
                    if (quickMsgData.get(position).getReply_images_arr() == null || quickMsgData.get(position).getReply_images_arr().size() <= 0) {
                        ChatUtil.getInstance().sendTxtMessage(quickMsgData.get(position).getMaincontent(), username,
                                chatType, receiveId, EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                        chatMsgListview.add();
                    } else {
                        // 下载图片，并发送
                        showLoading();
                        final int[] num = {0};
                        List<ChatQuickMsgBean.ReplyImagesArrBean> list = quickMsgData.get(position).getReply_images_arr();
                        for (ChatQuickMsgBean.ReplyImagesArrBean bean : list) {
                            DownLoadUtil.downLoadImg(bean.getImgurl(), new DownLoadUtil.OnDownLoadListener() {
                                @Override
                                public void success(String path) {
                                    ChatUtil.getInstance().sendImgMessage(getActivity(), path, username, chatType, receiveId, EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName,
                                            messageStatusCallback);
                                    chatMsgListview.add();
                                    num[0]++;
                                    if (num[0] >= list.size()) {
                                        hideLoading();
                                    }
                                }

                                @Override
                                public void fail() {

                                }
                            });
                        }
                    }
                }
            });
            // 申请录音权限
            registerVoicePermission();

            // 设置未读消息数量
            setMsgNum();
        } catch (Exception e) {
            e.printStackTrace();
            showError("用户数据异常，请稍后重试");
            getActivity().finish();
        }
    }

    @OnClick({R.id.tv_send, R.id.tv_title_right, R.id.iv_back, R.id.rl_quick_msg_add, R.id.rl_quick_msg_manager, R.id.tv_cancel, R.id.rl_delete,
            R.id.rl_forward, R.id.rl_down, R.id.rl_collect, R.id.rl_menu_custom_service, R.id.iv_to_custom_service, R.id.tv_assistant_menu_one
            , R.id.tv_assistant_menu_two, R.id.tv_noread_num})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_send:  // 发送文本消息
                if (isDelete()) {
                    if (!isService()) {
                        ChatUtil.getInstance().insertDeleteMessage(conversation, username, receiveId,
                                EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                        chatMsgListview.add();
                        etContent.setText("");
                        return;
                    }
                }
                ChatUtil.getInstance().sendTxtMessage(etContent.getText().toString(), username, chatType, receiveId,
                        EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                etContent.setText("");
                chatMsgListview.add();
                break;

            case R.id.tv_title_right: // 更多按钮
                if (userInfoBean == null) {
                    showError("未查询到用户信息，请稍后重试");
                    return;
                }
                if (userInfoBean.isAssistant()) {
                    startActivity(new Intent(getActivity(), UserInfoActivity.class)
                            .putExtra(UserInfoActivity.INTENT_USER_ID, getMember_id()));
                    return;
                }
                if (chatType == ChatConstant.CHATTYPE_SINGLE) {
                    // 单聊
                    startActivity(new Intent(getActivity(), ChatSettingActivity.class)
                            .putExtra(ChatSettingActivity.INTENT_USERINFO, userInfoBean.userInfoBean));
                } else if (chatType == ChatConstant.CHATTYPE_GROUP) {
                    // 群组聊天
                    Intent intent = new Intent(getActivity(), ChatGroupSettingActivity.class);
                    intent.putExtra(ChatGroupSettingActivity.GroupInfoBeanKeyGroupID, userInfoBean.groupInfoBean.getGroup_id());
                    startActivityForResult(intent, ChatActivity.REQUEST_CODE);
                } else { // 聊天室: 此功能暂不支持

                }
                break;

            case R.id.iv_back:
                getActivity().finish();
                break;

            case R.id.rl_quick_msg_add: // 添加快捷回复
                startActivity(new Intent(getActivity(), ChatQuickMsgAddActivity.class));
                break;

            case R.id.rl_quick_msg_manager: // 管理快捷回复
                startActivity(new Intent(getActivity(), ChatQuickMsgManagerActivity.class));
                break;

            case R.id.tv_cancel: // 取消多选模式
                setIsSelectMore(false);
                break;

            case R.id.rl_delete: // 多选-删除消息
                if (selectMoreList == null || selectMoreList.size() <= 0) {
                    showTips("提示", "请选择要删除的消息", null);
                    return;
                }
                for (int i = 0; i < selectMoreList.size(); i++) {
                    // 删除消息
                    conversation.removeMessage(chatMsgListview.getEmMessageList().get(i).getMsgId());
                }
                chatMsgListview.refresh();
                setIsSelectMore(false);
                break;

            case R.id.rl_forward: // 多选-转发消息
                forWardBySelect();
                break;

            case R.id.rl_down: // 多选-下载
                downLoadBySelect();
                break;

            case R.id.rl_collect: // 多选-收藏
                try {
                    collectBySelect();
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                break;

            case R.id.rl_menu_custom_service: // 客服模式下-切换按钮图标点击
                llCustomService.setVisibility(View.GONE);
                break;

            case R.id.iv_to_custom_service: // 客服模式下-切换到客服聊天按钮点击
                llCustomService.setVisibility(View.VISIBLE);
                break;

            case R.id.tv_assistant_menu_one: // 客服模式下-第一个菜单按钮点击
                try {
//                    if (bottomAsistantMentList == null || bottomAsistantMentList.size() <= 0) {
//                        return;
//                    }
                    mPresenter.getChatAssistantMessage(getActivity(), "menu", 1);
                } catch (Exception e) {
                    e.printStackTrace();
                    showError("暂未获取到菜单消息，请稍后重试");
                }
                break;

            case R.id.tv_assistant_menu_two: // 客服模式下-第二个菜单按钮点击
                try {
//                    if (bottomAsistantMentList == null || bottomAsistantMentList.size() <= 0) {
//                        return;
//                    }
//                    mPresenter.getChatAssistantMessage(getActivity(), "menu", bottomAsistantMentList.get(1).getMenu_id());
                    startActivity(new Intent(getActivity(), FeedBackActivity.class));
                } catch (Exception e) {
                    e.printStackTrace();
                    showError("暂未获取到菜单消息，请稍后重试");
                }
                break;

            case R.id.tv_noread_num: // 未读数量点击
                getActivity().finish();
                break;
        }
    }

    /**
     * 设置消息数量
     */
    private void setMsgNum() {
        getActivity().runOnUiThread(() -> {
            int num = EMClient.getInstance().chatManager().getUnreadMessageCount();
            if (num > 0) {
                tvNoreadNum.setText(num + "");
                tvNoreadNum.setVisibility(View.VISIBLE);
            } else {
                tvNoreadNum.setVisibility(View.GONE);
            }
        });

    }

    /**
     * 多选模式下收藏
     */
    private void collectBySelect() throws HyphenateException {
        if (selectMoreList == null || selectMoreList.size() <= 0) {
            showTips("提示", "请选择要收藏的消息", null);
            return;
        }
        if (selectMoreList.size() == 1) {
            EMMessage message = chatMsgListview.getEmMessageList().get(selectMoreList.get(0));
            if (message.getType() != EMMessage.Type.IMAGE && message.getType() != EMMessage.Type.TXT) {
                showTips("提示", "只能收藏图片及文本", null);
                return;
            }
        }
        List<EMMessage> list = new ArrayList<>();
        for (int i = 0; i < selectMoreList.size(); i++) {
            EMMessage message = chatMsgListview.getEmMessageList().get(selectMoreList.get(i));
            if (message.getType() == EMMessage.Type.TXT ) {
                list.add(chatMsgListview.getEmMessageList().get(selectMoreList.get(i)));
            }
            if (message.getType() == EMMessage.Type.CUSTOM){
                EMCustomMessageBody customBody = (EMCustomMessageBody) message.getBody();
                if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)) {
                    list.add(chatMsgListview.getEmMessageList().get(selectMoreList.get(i)));
                }
            }
        }
        if (list.size() <= 0) {
            showTips("提示", "只能收藏图片及文本", null);
        }
        for (EMMessage message : list) {
            String collectdetail = null;
            String collectimage = null;
            int id;
            if (message.direct() == EMMessage.Direct.SEND) {
                id = UserInfoUtil.getUserId();
            } else {
                id = message.getIntAttribute(ChatConstant.EXTRA_SEND_USER_ID);
            }
            if (message.getType() == EMMessage.Type.TXT) {
                EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                collectdetail = txtBody.getMessage();
                mPresenter.addChatCollect(getActivity(), collectdetail, collectimage, id);
            } if (message.getType() == EMMessage.Type.CUSTOM){
                EMCustomMessageBody customBody = (EMCustomMessageBody) message.getBody();
                if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)) {
                    downLoadChatImg(message, id);
                }
            }
        }
    }

    /**
     * 多选模式下下载图片
     */
    private void downLoadBySelect() {
        if (selectMoreList == null || selectMoreList.size() <= 0) {
            showTips("提示", "请选择要删除的消息", null);
            return;
        }
        if (selectMoreList.size() == 1) {
            EMMessage message = chatMsgListview.getEmMessageList().get(selectMoreList.get(0));
            if (message.getType()==EMMessage.Type.CUSTOM){
                EMCustomMessageBody customBody = (EMCustomMessageBody) message.getBody();
                if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)||customBody.event().equals(ChatConstant.EXTRA_CUSTOM_VIDEO)){

                }else {
                    showTips("提示", "只能下载图片和视频哦", null);
                    return;
                }
            }else {
                showTips("提示", "只能下载图片和视频哦", null);
                return;
            }
        }
        int sum = 0;
        List<EMMessage> list = new ArrayList<>();
        for (int i = 0; i < selectMoreList.size(); i++) {
            list.add(chatMsgListview.getEmMessageList().get(selectMoreList.get(i)));
            EMCustomMessageBody customBody = (EMCustomMessageBody) chatMsgListview.getEmMessageList().get(selectMoreList.get(i)).getBody();
            if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)||customBody.event().equals(ChatConstant.EXTRA_CUSTOM_VIDEO)){
                sum++;
            }
        }
        final int[] num = {0};
        showLoading();
        int finalSum = sum;
        DownLoadUtil.downLoadImg(list, new DownLoadUtil.OnDownLoadListener() {
            @Override
            public void success(String path) {
                getActivity().runOnUiThread(() -> {
                    num[0]++;
                    if (num[0] == finalSum) {
                        hideLoading();
                        showError("下载成功");
                        setIsSelectMore(false);
                    }
                });
            }

            @Override
            public void fail() {

            }
        });
    }

    /**
     * 多选模式下转发消息
     */
    private void forWardBySelect() {
        try {
            if (selectMoreList == null || selectMoreList.size() <= 0) {
                showTips("提示", "请选择要转发的消息", null);
                return;
            }
            // 无法转发语音，名片，消息
            if (selectMoreList.size() == 1) {
                EMMessage message = chatMsgListview.getEmMessageList().get(selectMoreList.get(0));
                if (message.getType() == EMMessage.Type.VOICE) {
                    showTips("提示", "无法转发语音、名片消息", null);
                    return;
                }
                if (message.getType() == EMMessage.Type.CUSTOM) {
                    EMCustomMessageBody messageBody = (EMCustomMessageBody) message.getBody();
                    if (messageBody.event() == ChatConstant.EXTRA_CUSTOM_SHARE) {
                        showTips("提示", "无法转发语音、名片消息", null);
                        return;
                    }
                }
            }
            startActivity(new Intent(getActivity(), ChatShareUserActivity.class)
                    .putExtra(ChatShareUserActivity.INTENT_FROM_TAG, 4));
        } catch (Exception e) {
            e.printStackTrace();
            setIsSelectMore(false);
        }
    }

    /**
     * 转发选择好友返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void selectUserResult(ChatShareUserEvent event) {
        if (isDelete()) {
            if (!isService()) {
                ChatUtil.getInstance().insertDeleteMessage(conversation, username, receiveId,
                        EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                chatMsgListview.add();
                return;
            }
        }
        if (event.getTag() == 4) {
            // TODO: 添加群组类型处理
            if (isItemForward) {
                // 消息列表单独转发
                List<EMMessage> messages = new ArrayList<>();
                messages.add(chatMsgListview.getEmMessageList().get(forwardPos));
                ChatUtil.getInstance().forWardBySelect(getActivity(), messages, event.getBean().getHxusername(), ChatConstant.CHATTYPE_SINGLE
                        , event.getBean().getMember_id(), EmptyUtils.isNotEmpty(event.getBean().getRemarks_name()) ? event.getBean().getRemarks_name() :
                                event.getBean().getNickname(), messageStatusCallback);
            } else {
                // 多选状态下转发
                List<EMMessage> messages = new ArrayList<>();
                for (int i = 0; i < selectMoreList.size(); i++) {
                    messages.add(chatMsgListview.getEmMessageList().get(selectMoreList.get(i)));
                }
                ChatUtil.getInstance().forWardBySelect(getActivity(), messages, event.getBean().getHxusername(), ChatConstant.CHATTYPE_SINGLE
                        , event.getBean().getMember_id(), EmptyUtils.isNotEmpty(event.getBean().getRemarks_name()) ? event.getBean().getRemarks_name() :
                                event.getBean().getNickname(), messageStatusCallback);
            }
            showError("发送成功");
            setIsSelectMore(false);
        }
    }

    /**
     * 设置是否是选择更多状态
     *
     * @param isSelectMore
     */
    private void setIsSelectMore(boolean isSelectMore) {
        if (!isSelectMore) {
            tvCancel.setVisibility(View.GONE);
            ivBack.setVisibility(View.VISIBLE);
            ivTitleRight.setVisibility(View.VISIBLE);
            isSecectMore = false;
            chatMsgListview.getMessageAdapter().setIsSelectMore(false);
            selectMoreList.clear();
            chatMsgListview.getMessageAdapter().setCheckBoxList(selectMoreList);
            llSelectMoreBottom.setVisibility(View.GONE);
        } else {
            isSecectMore = true;
            chatMsgListview.setIsSelectMore(true);
            tvCancel.setVisibility(View.VISIBLE);
            ivBack.setVisibility(View.GONE);
            ivTitleRight.setVisibility(View.GONE);
            llSelectMoreBottom.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 初始化菜单信息
     */
    private void initMenu() {
        menuList = new ArrayList<>();
        menuList.addAll(ChatUi.getInstance().initMenu(true));
        menuAdapter = new ChatBottomMenuAdapter(R.layout.rv_item_chat_bottom_menu, menuList);
        rvMenu.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        rvMenu.setAdapter(menuAdapter);
        menuAdapter.setOnItemClickListener(this);
    }

    private void initChatUi() {

        // 对方是客服，展示客服按钮
        if (hxUserInfoBean.getIs_assistant() == 1) {
            llCustomService.setVisibility(View.VISIBLE);
            ivToCustomService.setVisibility(View.VISIBLE);
            bottomAsistantMentList = new ArrayList<>();
//            mPresenter.getChatBottomAssistantMenu(getActivity());
        }

        quickMsgData = new ArrayList<>();
        quickMsgAdapter = new ChatQuickMsgAdapter(quickMsgData);
        rvQuickMsg.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
        rvQuickMsg.setAdapter(quickMsgAdapter);

        //mBtnAudio
        mUiHelper = ChatUiHelper.with(getActivity());
        mUiHelper.bindContentLayout(mainLayout)
                .bindttToSendButton(tvSend)
                .bindEditText(etContent)
                .bindBottomLayout(bottomLayout)
                .bindEmojiLayout(includeEmoji)
                .bindAddLayout(includeMenu)
                .bindToAddButton(ivMore)
                .bindToEmojiButton(ivEmoji)
                .bindAudioBtn(tvVoice)
                .bindAudioIv(ivVoice)
                .bindQuickMsgView(includeQuickMsg)
                .bindEmojiData()
                .setOnChatUiHelperListener(this);

        //点击空白区域关闭键盘
        chatMsgListview.getRvMsg().setOnTouchListener((view, motionEvent) -> {
            mUiHelper.hideBottomLayout(false);
            mUiHelper.hideSoftInput();
            etContent.clearFocus();
            ivEmoji.setImageResource(R.mipmap.ic_icon_chat_emoji);
            return false;
        });
        // 发送语音消息
        tvVoice.setOnFinishedRecordListener((audioPath, time) -> {
            File file = new File(audioPath);
            if (file.exists()) {
                if (isDelete()) {
                    if (!isService()) {
                        ChatUtil.getInstance().insertDeleteMessage(conversation, username, receiveId,
                                EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                        chatMsgListview.add();
                        return;
                    }
                }
                ChatUtil.getInstance().sendVoiceMessage(file.getPath(), time, username, chatType, receiveId,
                        EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                chatMsgListview.add();
            }
        });

        // 发送语音按钮触摸
        tvVoice.setOnVoiceTouchListener(() -> registerVoicePermission());

        // 设置选择更多状态下，选中或未选中
        chatMsgListview.getMessageAdapter().setOnItemClickListener((adapter, view, position) -> {
            if (!isSecectMore) {
                return;
            }
            boolean isAdd = true;
            int index = 0;
            for (int i = 0; i < selectMoreList.size(); i++) {
                if (selectMoreList.get(i) == position) {
                    isAdd = false;
                    index = i;
                    break;
                }
            }
            if (isAdd) {
                selectMoreList.add(position);
            } else {
                selectMoreList.remove(index);
            }
            LogUtils.d(new Gson().toJson(selectMoreList) + "    size:" + chatMsgListview.getEmMessageList().size());
            chatMsgListview.getMessageAdapter().setCheckBoxList(selectMoreList);
        });
    }

    /**
     * 获取权限
     */
    private void registerVoicePermission() {
        premisionTag = 2;
        PermissionGen.with(this)
                .addRequestCode(Common.BASIC_PERMISSION_REQUEST_CODE)
                .permissions(Manifest.permission.RECORD_AUDIO)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    protected EMCallBack messageStatusCallback = new EMCallBack() {
        @Override
        public void onSuccess() {
            LogUtils.d("发送成功");
            hideLoading();
            chatMsgListview.refresh();
        }

        @Override
        public void onError(int i, String s) {
            hideLoading();
            LogUtils.d("发送失败：" + i + "   msg:" + s);
            handleBlack(i);
        }

        @Override
        public void onProgress(int i, String s) {
            LogUtils.d("发送中：" + i + "   msg:" + s);
            chatMsgListview.refresh();
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(ForwardEvent event) {
        if (event.errorCode==0){
            chatMsgListview.refresh();
        }else {
            handleBlack(event.errorCode);
        }
    }


    private void handleBlack(int i) {
        if (i == 210) {
            // 对方把自己加入黑名单
            EMMessage message = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
            EMCustomMessageBody customBody = new EMCustomMessageBody(ChatConstant.EXTRA_CUSTOM_BLACK);
            message.addBody(customBody);
            message.setTo(username);
            message.setAttribute(ChatConstant.EXTRA_SEND_USER_ID, UserInfoUtil.getUserId());
            message.setAttribute(ChatConstant.EXTRA_SEND_USER_NICKNAME, UserInfoUtil.getUserNickName());
            message.setAttribute(ChatConstant.EXTRA_RECEIVE_USER_ID, receiveId);
            message.setAttribute(ChatConstant.EXTRA_RECEIVE_USER_NICKNAME, receiveName);
            conversation.insertMessage(message);
        }
        chatMsgListview.add();
    }

    /**
     * 菜单选择
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        switch (menuList.get(position).getTag()) {
            case ChatMoreMenuBean.TAG_PHOTO: // 相册
                PhotoUtil.showPhoto(getActivity(), PictureMimeType.ofAll(), PictureConfig.MULTIPLE, false, false, null, this);
                break;

            case ChatMoreMenuBean.TAG_CAMERA: // 拍照
                premisionTag = 4;
                PermissionGen.with(this)
                        .addRequestCode(Common.BASIC_PERMISSION_REQUEST_CODE)
                        .permissions(Manifest.permission.CAMERA)
                        .request();

//                PhotoUtil.showCamera(getActivity(), PictureMimeType.ofImage(), PictureConfig.SINGLE, false, false, null, this);
                break;

            case ChatMoreMenuBean.TAG_LOCATION: // 位置
                premisionTag = 1;
                registerLocationPermission();
                break;

            case ChatMoreMenuBean.TAG_USER: // 个人名片
                startActivity(new Intent(getActivity(), ChatShareUserActivity.class)
                        .putExtra(ChatShareUserActivity.INTENT_NICK_NAME, receiveName)
                        .putExtra(ChatShareUserActivity.INTENT_FROM_TAG, 0));
                break;

            case ChatMoreMenuBean.TAG_COLLECT: // 收藏
                startActivity(new Intent(getActivity(), ChatCollectActivity.class)
                        .putExtra(ChatCollectActivity.INTENT_HEAD, receiveHead)
                        .putExtra(ChatCollectActivity.INTENT_NICKNAME, receiveName));
                break;

            case ChatMoreMenuBean.TAG_QUICK_MSG: // 快捷回复
                mUiHelper.showQuickMsgView();
                break;
        }
    }

    /**
     * 获取位置权限
     */
    private void registerLocationPermission() {
        PermissionGen.with(this)
                .addRequestCode(Common.BASIC_PERMISSION_REQUEST_CODE)
                .permissions(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE)
                .request();
    }

    @PermissionFail(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openFail() {
        ToastUtils.show("权限获取失败,请先设置权限");
    }


    @PermissionSuccess(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openSuccess() {
        if (premisionTag == 1) {
            // 位置权限申请成功，到位置页面
            LogUtils.d("地区权限申请成功，到位置界面");
            startActivity(new Intent(getActivity(), ChatLocationActivity.class));
        } else if (premisionTag == 2) {
            // 录音权限获取成功
            tvVoice.setIsReady(true);
        } else if (premisionTag == 3) {
            // 电话权限申请成功，拨打电话
//            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + callPhone));
//            startActivity(intent);
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri uri = Uri.parse("tel:" + callPhone);
            intent.setData(uri);
            startActivity(intent);
        }else if (premisionTag ==4){
            startActivity(new Intent(getActivity(), CameraActivity.class));
            AnimUtil.overrideSlideUpOpenAnimation(getActivity());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCapture(ImageEvent event){
        if (event==null){
            return;
        }
        LogUtils.i("path:" + event.path);
        if (isDelete()) {
            if (!isService()) {
                ChatUtil.getInstance().insertDeleteMessage(conversation, username, receiveId,
                        EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                chatMsgListview.add();
                return;
            }
        }
//                EventBus.getDefault().post(new SendImageMessageEvent(PhotoUtil.getPath(media),username,chatType,receiveId,
//                        EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName,messageStatusCallback));
        ChatUtil.getInstance().sendImgMessage(getActivity(), event.path, username, chatType, receiveId,
                EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName,
                messageStatusCallback);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideo(VideoEvent event){
        if (event==null){
            return;
        }
        LogUtils.i("path:" + event.path);
        if (isDelete()) {
            if (!isService()) {
                ChatUtil.getInstance().insertDeleteMessage(conversation, username, receiveId,
                        EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                chatMsgListview.add();
                return;
            }
        }
        chatMsgListview.postDelayed(new Runnable() {
            @Override
            public void run() {
                showLoading();
            }
        },500);
        ChatUtil.getInstance().sendVideoMessage(getActivity(), event.path,event.imagePath, username, chatType, receiveId,
                EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName,
                messageStatusCallback);
    }

    /**
     * 拍照或选取照片返回
     *
     * @param result
     */
    @Override
    public void onResult(List<LocalMedia> result) {
        for (LocalMedia media : result) {
            if (PictureMimeType.getMimeType(media.getMimeType()) == PictureConfig.TYPE_VIDEO) {
                if (isDelete()) {
                    if (!isService()) {
                        ChatUtil.getInstance().insertDeleteMessage(conversation, username, receiveId,
                                EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                        chatMsgListview.add();
                        return;
                    }
                }
                String path = PhotoUtil.getPath(media);
                chatMsgListview.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showLoading();
                    }
                },500);
                ChatUtil.getInstance().sendVideoMessage(getActivity(), path,getVideoThumb(path,getActivity()), username, chatType, receiveId,
                        EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName,
                        messageStatusCallback);
            } else {
                LogUtils.i("path:" + PhotoUtil.getPath(media));
                if (isDelete()) {
                    if (!isService()) {
                        ChatUtil.getInstance().insertDeleteMessage(conversation, username, receiveId,
                                EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                        chatMsgListview.add();
                        return;
                    }
                }
//                EventBus.getDefault().post(new SendImageMessageEvent(PhotoUtil.getPath(media),username,chatType,receiveId,
//                        EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName,messageStatusCallback));
                ChatUtil.getInstance().sendImgMessage(getActivity(), PhotoUtil.getPath(media), username, chatType, receiveId,
                        EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName,
                        messageStatusCallback);
            }
            chatMsgListview.add();
        }
    }

    public static String getVideoThumb(String path, Activity context) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        String url;
        File file = new File(path);
        if (file.exists()) {
            url = file.getPath();
        } else {
            url = FileUtils.getImageAbsolutePath(context, Uri.parse(path));
        }
        media.setDataSource(url);
        Bitmap frameAtTime = media.getFrameAtTime();
       return CameraActivity.saveBitmap(frameAtTime,CameraActivity.IMAGE_PATH,null);
    }

    @Override
    public void onCancel() {

    }

    /**
     * 收到信消息
     *
     * @param list
     */
    @Override
    public void onMessageReceived(List<EMMessage> list) {
        for (EMMessage message : list) {
            String username = null;
            // group message
            if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                username = message.getTo();
            } else {
                // single chat message
                username = message.getFrom();
            }
            LogUtils.d("from:" + username);
            LogUtils.d("username:" + this.username);
            // if the message is for current conversation
            if (username.equals(this.username) || message.getTo().equals(this.username) || message.conversationId().equals(this.username)) {
                conversation.markMessageAsRead(message.getMsgId());
                chatMsgListview.add();
                if (!AppHelper.isBackground(getActivity())) {
                    conversation.markMessageAsRead(message.getMsgId());
                    // 重置桌面小红点数量
                    int num = EMClient.getInstance().chatManager().getUnreadMessageCount();
                    if (num > 0) {
                        BadgeUtil.setBadgeCount(getActivity(), num, R.mipmap.ic_launcher);
                    } else {
                        BadgeUtil.resetBadgeCount(getActivity(), R.mipmap.ic_launcher);
                    }
                }
            }
        }
        setMsgNum();
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {
//        setMsgNum();
        onMessageReceived(list);
    }

    @Override
    public void onMessageRead(List<EMMessage> list) {
        LogUtils.d("收到已读回执消息");
        chatMsgListview.refresh();
    }


//    @Override
//    public void onGroupMessageRead(List<EMGroupReadAck> var1) {
//        chatMsgListview.refresh();
//    }
//
//    @Override
//    public void onReadAckForGroupMessageUpdated() {
//        chatMsgListview.refresh();
//    }

    @Override
    public void onMessageDelivered(List<EMMessage> list) {
        chatMsgListview.refresh();
    }

    @Override
    public void onMessageRecalled(List<EMMessage> list) {
        chatMsgListview.refresh();
        setMsgNum();
    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {
        chatMsgListview.refresh();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(this);
//        EMClient.getInstance().groupManager().removeGroupChangeListener();
    }

    /**
     * 搜索成功，跳转到pos
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void searchSuccess(ChatSearchMsgEvent event) {
        chatMsgListview.searchSuccess(event.getMessage());
    }

    /**
     * 刷新列表
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void chatRefresh(ChatMessageListRefreshEvent event) {
        chatMsgListview.refresh();
    }


    /**
     * 发送位置信息
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sendLocation(ChatLocationEvent event) {
        if (isDelete()) {
            if (!isService()) {
                ChatUtil.getInstance().insertDeleteMessage(conversation, username, receiveId,
                        EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                chatMsgListview.add();
                return;
            }
        }
        ChatUtil.getInstance().sendLocationMessage(event.getBean(), username, chatType, receiveId,
                EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
        chatMsgListview.add();
    }

    /**
     * 用户信息获取成功
     *
     * @param data
     */
    @Override
    public void userInfoResult(UserInfoBean data, int tag) {
//        if (data == null) {
//            return;
//        }
        if (tag == 1) {
            if (data.getIs_buddy() == 1) {
                if (data.getIs_del() == 1) {
                    startActivity(new Intent(getActivity(), AddFriendActivity.class)
                            .putExtra(AddFriendActivity.INTENT_USER_ID, data.getMember_id()));
                } else {
                    startActivity(new Intent(getActivity(), UserInfoActivity.class)
                            .putExtra(UserInfoActivity.INTENT_USER_ID, data.getMember_id()));
                }
            } else {
                startActivity(new Intent(getActivity(), AddFriendActivity.class)
                        .putExtra(AddFriendActivity.INTENT_USER_ID, data.getMember_id()));
            }
            return;
        }
        userInfoBean = new ChatInfoAdapterBean(data);
        // 会员才设置在线时间
        if (UserInfoUtil.getUserIsVip()) {
            // 设置在线时间
            if (EmptyUtils.isNotEmpty(data.getOnline_time())) {
                tvOnlineState.setText(data.getOnline_time());
                tvOnlineState.setVisibility(View.VISIBLE);
            }
        }
        if (userInfoBean.isAssistant()) {
            ivTitleRight.setImageResource(R.mipmap.ic_chat_title_assistant);
            llCustomService.setVisibility(View.VISIBLE);
            ivToCustomService.setVisibility(View.VISIBLE);

            // 超过12个小时才调用接口
            long lastTime = (long) SPUtils.get(getActivity(), Common.CHAT_CUSTOM_ASSISTANT_TIME, 0L);
            if (System.currentTimeMillis() - lastTime >= (1000 * 60 * 60 * 12)) {
                SPUtils.put(getActivity(), Common.CHAT_CUSTOM_ASSISTANT_TIME, System.currentTimeMillis());
                mPresenter.sendCustomServiceMsg(getActivity());
            }
        } else {
            ivTitleRight.setImageResource(R.mipmap.ic_icon_title_more);
        }

    }

    @Override
    public void groupInfo(GroupInfoBean data) {
        GroupInfoBeanLiveData.update(data);
        Log.i("groupChat", "groupInfo: " + data);
        data.save();
        reStatus(data);

//        if (tag == 1) {
//            if (data.getIs_buddy() == 1) {
//                if (data.getIs_del() == 1) {
//                    startActivity(new Intent(getActivity(), AddFriendActivity.class)
//                            .putExtra(AddFriendActivity.INTENT_USER_ID, data.getMember_id()));
//                } else {
//                    startActivity(new Intent(getActivity(), UserInfoActivity.class)
//                            .putExtra(UserInfoActivity.INTENT_USER_ID, data.getMember_id()));
//                }
//            } else {
//                startActivity(new Intent(getActivity(), AddFriendActivity.class)
//                        .putExtra(AddFriendActivity.INTENT_USER_ID, data.getMember_id()));
//            }
//            return;
//        }
//
//        // 会员才设置在线时间
//        if (UserInfoUtil.getUserIsVip()) {
//            // 设置在线时间
//            if (EmptyUtils.isNotEmpty(data.getOnline_time())) {
//                tvOnlineState.setText(data.getOnline_time());
//                tvOnlineState.setVisibility(View.VISIBLE);
//            }
//        }
//        if (userInfoBean.isAssistant()) {
//            ivTitleRight.setImageResource(R.mipmap.ic_chat_title_assistant);
//            llCustomService.setVisibility(View.VISIBLE);
//            ivToCustomService.setVisibility(View.VISIBLE);
//
//            // 超过12个小时才调用接口
//            long lastTime = (long) SPUtils.get(getActivity(), Common.CHAT_CUSTOM_ASSISTANT_TIME, 0L);
//            if (System.currentTimeMillis() - lastTime >= (1000 * 60 * 60 * 12)) {
//                SPUtils.put(getActivity(), Common.CHAT_CUSTOM_ASSISTANT_TIME, System.currentTimeMillis());
//                mPresenter.sendCustomServiceMsg(getActivity());
//            }
//        } else {
//            ivTitleRight.setImageResource(R.mipmap.ic_icon_title_more);
//        }
    }

    /**
     * 收藏成功
     */
    @Override
    public void collectSuccess() {
        showError("收藏成功");
    }

    /**
     * 图片上传成功
     *
     * @param data
     * @param id
     */
    @Override
    public void upLoadImgSuccess(UpLoadImgBean data, int id) {
        mPresenter.addChatCollect(getActivity(), null, data.getUrl(), id);
    }

    /**
     * 快捷回复列表获取成功
     *
     * @param data
     */
    @Override
    public void qucikMsgResult(List<ChatQuickMsgBean> data) {
        try {
            quickMsgData.clear();
            quickMsgData.addAll(data);
            quickMsgAdapter.notifyDataSetChanged();
            if (quickMsgData.size() > 0) {
                llQuickMsgNull.setVisibility(View.GONE);
            } else {
                llQuickMsgNull.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 官方客服号消息发送成功
     */
    @Override
    public void sendCustomServiceSuccess() {
        LogUtils.d("官方客服号消息发送成功");
    }

    /**
     * 官方底部菜单消息获取成功
     *
     * @param data
     */
    @Override
    public void chatBottomAssistantMenuResult(List<ChatBottomAssistantMenuBean> data) {
        try {
            bottomAsistantMentList = data;
            tvAssistantMenuOne.setText(data.get(0).getName());
            tvAssistantMenuTwo.setText(data.get(1).getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取官方消息成功
     */
    @Override
    public void getAssistantMsgSuccess() {
        LogUtils.d("官方消息获取成功");
    }

    /**
     * 根据二维码获取用户信息成功
     *
     * @param data
     */
    @Override
    public void userInfoResult(UserInfoBean data) {
        if (data.getMember_id() == UserInfoUtil.getUserId()) {
            startActivity(new Intent(getActivity(), MineUserInfoActivity.class));
            return;
        }
        if (data.getIs_buddy() == 1) {
            startActivity(new Intent(getActivity(), UserInfoActivity.class)
                    .putExtra(UserInfoActivity.INTENT_USER_ID, data.getMember_id()));
        } else {
            startActivity(new Intent(getActivity(), AddFriendActivity.class)
                    .putExtra(AddFriendActivity.INTENT_USER_ID, data.getMember_id())
                    .putExtra(AddFriendActivity.INTENT_TYPE, 2));
        }
    }

    /**
     * 根据二维码获取用户信息失败
     */
    @Override
    public void onFail() {

    }

    /**
     * 刷新快捷回复列表
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshQuickMsg(ChatQuickMsgRefreshEvent event) {
        if (event.getTag() == 0 || event.getTag() == 3) {
            mPresenter.getChatQuickMsgList(getActivity());
        } else if (event.getTag() == 1) {
            quickMsgData.remove(event.getPos());
            quickMsgAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 分享名片
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void shareUser(ChatShareUserEvent event) {
        if (event.getTag() == 0) {
            LogUtils.d("分享名片");
            if (isDelete()) {
                if (!isService()) {
                    ChatUtil.getInstance().insertDeleteMessage(conversation, username, receiveId,
                            EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                    chatMsgListview.add();
                    return;
                }
            }
            //FIXME: 需要兼容群组
            if (chatType == ChatConstant.CHATTYPE_SINGLE) {
                ChatShareUserDialog shareUserDialog = new ChatShareUserDialog(getActivity(), userInfoBean.userInfoBean, event.getBean(), (bean, remark) -> {
                    ChatUtil.getInstance().sendShareUserMessage(bean.getNickname(), bean.getMember_id(), bean.getAvatar(), bean.getChatnumber(), remark, username
                            , chatType, receiveId, EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                    chatMsgListview.add();
                });
                shareUserDialog.show();
            } else {
                GroupInfoBean groupInfoBean = userInfoBean.groupInfoBean;
                ChatShareUserDialog shareUserDialog = new ChatShareUserDialog(getActivity(), groupInfoBean, event.getBean(), (bean, remark) -> {
                    ChatUtil.getInstance().sendShareUserMessage(bean.getNickname(), bean.getMember_id(), bean.getAvatar(), bean.getChatnumber(), remark, username
                            , chatType, receiveId, EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                    chatMsgListview.add();
                });
                shareUserDialog.show();
            }
        }
    }

    /**
     * 更新自定义表情
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateEmojiLike(ChatEmojiLikeEvent event) {
        mUiHelper.updateEmojiLike();
    }

    /**
     * 发送自定义表情
     *
     * @param path
     */
    @Override
    public void sendEmoji(String path) {
        if (isDelete()) {
            if (!isService()) {
                ChatUtil.getInstance().insertDeleteMessage(conversation, username, receiveId,
                        EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                chatMsgListview.add();
                return;
            }
        }
        ChatUtil.getInstance().sendImgMessage(getActivity(), path, username, chatType, receiveId, EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName,
                messageStatusCallback);
        chatMsgListview.add();
    }

    /**
     * 消息列表长按事件
     *
     * @param message
     */
    private PopupWindowList popupWindowList;

    /**
     * 消息列表长按事件
     *
     * @param message
     * @param view
     */
    @Override
    public void onMsgLongClick(EMMessage message, View view, int pos) {
        if (isSecectMore) {
            // 更多状态下，不进行操作
            return;
        }
        List<String> dataList = new ArrayList<>();
        if (message.direct() == EMMessage.Direct.SEND) {
            if (message.getType() == EMMessage.Type.TXT) {
                dataList.add("复制");
            }
            if (message.getType() == EMMessage.Type.TXT || message.getType() == EMMessage.Type.IMAGE) {
                dataList.add("收藏");
            }
            if (message.getType() == EMMessage.Type.CUSTOM) {
                EMCustomMessageBody customMessageBody = (EMCustomMessageBody) message.getBody();
                if (customMessageBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)) {
                    dataList.add("收藏");
                }
            }
            dataList.add("转发");
            dataList.add("撤回");
            dataList.add("删除");
        } else {
            if (message.getType() == EMMessage.Type.TXT) {
                dataList.add("复制");
            }
            if (message.getType() == EMMessage.Type.TXT || message.getType() == EMMessage.Type.IMAGE) {
                dataList.add("收藏");
            }
            if (message.getType() == EMMessage.Type.CUSTOM) {
                EMCustomMessageBody customMessageBody = (EMCustomMessageBody) message.getBody();
                if (customMessageBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)) {
                    dataList.add("收藏");
                }
            }
            dataList.add("删除");
        }
        if (message.getType() == EMMessage.Type.VOICE) {
            dataList.remove("转发");
        }
        if (message.getType() == EMMessage.Type.IMAGE) {
            dataList.add("下载");
        }
        if (message.getType() == EMMessage.Type.CUSTOM) {
            EMCustomMessageBody customMessageBody = (EMCustomMessageBody) message.getBody();
            if (customMessageBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)||customMessageBody.event().equals(ChatConstant.EXTRA_CUSTOM_VIDEO)) {
                dataList.add("下载");
            }
        }
        dataList.add("更多");
        popupWindowList = new PopupWindowList(view.getContext());
        popupWindowList.setAnchorView(view);
        popupWindowList.setItemData(dataList);
        popupWindowList.setModal(false);
        popupWindowList.show();
        popupWindowList.setOnItemClickListener((adapterView, view1, i, l) -> {
            switch (dataList.get(i)) {
                case "删除":
                    // 删除消息
                    conversation.removeMessage(message.getMsgId());
                    chatMsgListview.refresh();
                    break;

                case "复制":
                    // 复制文本
                    AppHelper.copy(getActivity(), ((EMTextMessageBody) message.getBody()).getMessage());
                    showError("复制成功");
                    break;

                case "收藏":
                    try {
                        // 收藏
                        String collectdetail = null;
                        String collectimage = null;
                        int id;
                        if (message.direct() == EMMessage.Direct.SEND) {
                            id = UserInfoUtil.getUserId();
                        } else {
                            id = message.getIntAttribute(ChatConstant.EXTRA_SEND_USER_ID);
                        }
                        if (message.getType() == EMMessage.Type.TXT) {
                            EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                            collectdetail = txtBody.getMessage();
                            mPresenter.addChatCollect(getActivity(), collectdetail, collectimage, id);
                        } else if (message.getType() == EMMessage.Type.IMAGE) {
                            downLoadChatImg(message, id);
                        } else if (message.getType() == EMMessage.Type.CUSTOM) {
                            EMCustomMessageBody messageBody = (EMCustomMessageBody) message.getBody();
                            if (messageBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)) {
                                downLoadChatImg(message, id);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case "撤回":
                    try {
                        EMClient.getInstance().chatManager().recallMessage(message);
                        // 撤回消息
                        ChatUtil.getInstance().sendRecallMessage(username, chatType, receiveId,
                                EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                        chatMsgListview.add();
                    } catch (Exception e) {
                        e.printStackTrace();
                        showError("撤回消息失败");
                    }

                    break;

                case "更多":
                    isItemForward = false;
                    setIsSelectMore(true);
                    break;

                case "转发":
                    forwardPos = pos;
                    isItemForward = true;
                    startActivity(new Intent(getActivity(), ChatShareUserActivity.class)
                            .putExtra(ChatShareUserActivity.INTENT_FROM_TAG, 4));
                    break;

                case "下载":
                    List<EMMessage> list = new ArrayList<>();
                    list.add(message);
                    showLoading();
                    DownLoadUtil.downLoadImg(list, new DownLoadUtil.OnDownLoadListener() {
                        @Override
                        public void success(String path) {
                            getActivity().runOnUiThread(() -> {
                                showError("下载成功");
                                hideLoading();
                            });
                        }

                        @Override
                        public void fail() {

                        }
                    });
                    break;
            }
            popupWindowList.hide();
        });

//        ChatMsgLongClickDialog longClickDialog = new ChatMsgLongClickDialog(getActivity(), message, new ChatMsgLongClickDialog.OnMsgLongClickMenuClickListener() {
//            @Override
//            public void delete(EMMessage message) {
//                // 删除消息
//                conversation.removeMessage(message.getMsgId());
//                chatMsgListview.refresh();
//            }
//
//            @Override
//            public void copy(EMMessage message) {
//                // 复制文本
//                AppHelper.copy(getActivity(), ((EMTextMessageBody) message.getBody()).getMessage());
//            }
//
//            @Override
//            public void collect(EMMessage message) {
//                try {
//                    // 收藏
//                    String collectdetail = null;
//                    String collectimage = null;
//                    int id;
//                    if (message.direct() == EMMessage.Direct.SEND) {
//                        id = UserInfoUtil.getUserId();
//                    } else {
//                        id = message.getIntAttribute(ChatConstant.EXTRA_SEND_USER_ID);
//                    }
//                    if (message.getType() == EMMessage.Type.TXT) {
//                        EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
//                        collectdetail = txtBody.getMessage();
//                        mPresenter.addChatCollect(getActivity(), collectdetail, collectimage, id);
//                    } else if (message.getType() == EMMessage.Type.IMAGE) {
//                        downLoadChatImg(message, id);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//
//            }
//
//            @Override
//            public void reCall(EMMessage message) {
//                try {
//                    // 撤回消息
//                    ChatUtil.getInstance().sendRecallMessage(username, chatType, receiveId,
//                            EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
//                    EMClient.getInstance().chatManager().recallMessage(message);
//                    chatMsgListview.refresh();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//        longClickDialog.show();
    }

    /**
     * 头像点击
     *
     * @param userId
     * @param isMine
     */
    @Override
    public void onUserHeadClick(int userId, boolean isMine) {
        if (chatType == ChatConstant.CHATTYPE_SINGLE) {
            if (isMine) {
                startActivity(new Intent(getActivity(), MineUserInfoActivity.class));
            } else {
//            startActivity(new Intent(getActivity(), UserInfoActivity.class)
//                    .putExtra(UserInfoActivity.INTENT_USER_ID, userId));
                mPresenter.getUserInfo(getActivity(), userId, 1, true);
            }
        } else {
//            userInfoBean.groupInfoBean.m
//            MembersBean membersBean = membersBeans.get(i);
            if (isMine) {   // 点击的群成员是自己
                startActivity(new Intent(getActivity(), MineUserInfoActivity.class));
                return;
            }

            LitePal.findAllAsync(FriendBean.class, true).listen(new FindMultiCallback<FriendBean>() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onFinish(List<FriendBean> list) {
                    for (FriendBean friend: list) {
                        for (FriendCityBean friendCityBean: friend.getCity()) {
                            if (friendCityBean.getMember_id() == userId) {  // 好友
                                startActivity(new Intent(getActivity(), UserInfoActivity.class)
                                        .putExtra(UserInfoActivity.INTENT_USER_ID, userId));
                                return;
                            }
                        }
                    }
                    //  陌生人
                    Intent intent = new Intent(getActivity(), AddFriendActivity.class);
                    intent.putExtra(AddFriendActivity.INTENT_USER_ID, userId);
                    intent.putExtra(AddFriendActivity.INTENT_TYPE, 2);
                    if (userInfoBean.groupInfoBean.getProtectedswitch() == 1) {
                        intent.putExtra(AddFriendActivity.PROTECT_GROUP_MEMBER, true);
                    }
                    startActivity(intent);
                }
            });
        }
    }

    /**
     * 列表图片点击
     *
     * @param message
     */
    @Override
    public void onImageOnClick(EMMessage message, View view) {
        try {
            // 先获取所有的图片
            List<EMMessage> msgList = new ArrayList<>();
            msgList.addAll(conversation.searchMsgFromDB(EMMessage.Type.IMAGE, System.currentTimeMillis(), conversation.getAllMsgCount(),
                    null, EMConversation.EMSearchDirection.UP));

            // 在添加所有图片到list
            List<String> imgList = new ArrayList<>();
            for (EMMessage msg : msgList) {
                EMImageMessageBody imgBody = (EMImageMessageBody) msg.getBody();
                if (msg.direct() == EMMessage.Direct.SEND) {
                    File file = new File(imgBody.getLocalUri().getPath());
                    if (file.exists()) {
                        imgList.add(imgBody.getLocalUri().getPath());
                    } else {
                        imgList.add(imgBody.getRemoteUrl());
                    }
                } else {
                    imgList.add(imgBody.getRemoteUrl());
                }
            }

            // 判断当前的pos
            int pos = 0;
            EMImageMessageBody imgBody = (EMImageMessageBody) message.getBody();
            String imgPath;
            if (message.direct() == EMMessage.Direct.SEND) {
                File file = new File(imgBody.getLocalUri().getPath());
                if (file.exists()) {
                    imgPath = imgBody.getLocalUri().getPath();
                } else {
                    imgPath = imgBody.getRemoteUrl();
                }
            } else {
                imgPath = imgBody.getRemoteUrl();
            }
            for (int i = 0; i < imgList.size(); i++) {
                if (imgList.get(i).equals(imgPath)) {
                    pos = i;
                }
            }

            // 展示图片
            imageViewer.overlayStatusBar(true)
                    .imageData(imgList)
                    .setOnItemLongPressListener((position, imageView) -> {
                        saveImgToPhoto(imageView);
                        return false;
                    })
                    .watch(pos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onVideoOnClick(EMMessage message, View view) {

    }

    /**
     * 自定义图片消息点击
     *
     * @param message
     * @param view
     */
    @Override
    public void onImageCustomOnClick(EMMessage message, View view) {
        try {
            if (((EMCustomMessageBody) message.getBody()).event().equals(ChatConstant.EXTRA_CUSTOM_VIDEO)) {
                String path = message.getStringAttribute(ChatConstant.EXTRA_VIDEO_PATH);
                Intent intent = new Intent(getActivity(), VideoPalyActivity.class);
                intent.putExtra(VideoPalyActivity.VIDEO_URL, path);
                startActivity(intent);
                EventBus.getDefault().postSticky(new VideoMessageEvent(message));
                return;
            } else {
                // 先获取所有的图片
                conversation = EMClient.getInstance().chatManager().getConversation(username, ChatUtil.getConversationType(chatType), true);
                List<EMMessage> msgList = new ArrayList<>();
                msgList.addAll(conversation.searchMsgFromDB(EMMessage.Type.CUSTOM, System.currentTimeMillis(), conversation.getAllMsgCount(),
                        null, EMConversation.EMSearchDirection.UP));
//        // 在添加所有图片到list
//        List<String> imgList = new ArrayList<>();
//        for (EMMessage msg : msgList) {
//            EMImageMessageBody imgBody = (EMImageMessageBody) msg.getBody();
//            if (msg.direct() == EMMessage.Direct.SEND) {
//                File file = new File(imgBody.getLocalUri().getPath());
//                if (file.exists()) {
//                    imgList.add(imgBody.getLocalUri().getPath());
//                } else {
//                    imgList.add(imgBody.getRemoteUrl());
//                }
//            } else {
//                imgList.add(imgBody.getRemoteUrl());
//            }
//        }

                List<String> imgList = new ArrayList<>();
                for (EMMessage msg : msgList) {
                    EMCustomMessageBody customBody = (EMCustomMessageBody) msg.getBody();
                    if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)) {
                        // 只有是自定义图片类型才添加进去
                        String path = msg.getStringAttribute(ChatConstant.EXTRA_IMAGE_PATH);
                        String localPath = msg.getStringAttribute(ChatConstant.EXTRA_IMAGE_LOCAL_PATH);
                        if (msg.direct() == EMMessage.Direct.SEND) {
                            File file = new File(localPath);
                            if (file.exists()) {
                                imgList.add(localPath);
                            } else {
                                imgList.add(path);
                            }
                        } else {
                            imgList.add(path);
                        }
                    }
                }

                // 判断当前的pos
                int pos = 0;
                String path = message.getStringAttribute(ChatConstant.EXTRA_IMAGE_PATH);
                String localPath = message.getStringAttribute(ChatConstant.EXTRA_IMAGE_LOCAL_PATH);
                String imgPath;
                if (message.direct() == EMMessage.Direct.SEND) {
                    File file = new File(localPath);
                    if (file.exists()) {
                        imgPath = localPath;
                    } else {
                        imgPath = path;
                    }
                } else {
                    imgPath = path;
                }
                for (int i = 0; i < imgList.size(); i++) {
                    if (imgList.get(i).equals(imgPath)) {
                        pos = i;
                    }
                }
                // 展示图片
                imageViewer.overlayStatusBar(true)
                        .imageData(imgList)
                        .setOnItemLongPressListener((position, imageView) -> {
                            saveImgToPhoto(imageView);
                            return false;
                        })
                        .watch(pos);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存图片到相册
     */
    private void saveImgToPhoto(ImageView imageView) {
        List<String> list = new ArrayList<>();
        list.add("保存到相册");
        list.add("识别图中二维码");
        PublicRoundDialog roundDialog = new PublicRoundDialog(getActivity(), list, new OnPublicMenuOnClickListener() {
            @Override
            public void menuOnClick(int pos, String menu) {
                switch (menu) {
                    case "保存到相册":
                        ImageUtil.saveMyBitmap(getActivity(), ((BitmapDrawable) imageView.getDrawable()).getBitmap(), "chat_" + System.currentTimeMillis() + ".jpg");
                        break;
                    case "识别图中二维码":
                        new Thread(() -> {
                            Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
                            String result = QRCodeParseUtils.syncDecodeQRCode(bitmap);
                            Message msg = new Message();
                            msg.what = 0x02;
                            msg.obj = result;
                            handler.sendMessage(msg);
                        }).start();
                        break;
                }
            }
        });
        roundDialog.show();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x02) {
                String result = msg.obj == null ? null : (String) msg.obj;
                LogUtils.d(result);
                if (EmptyUtils.isEmpty(result)) {
                    showError("未识别到二维码信息");
                    return;
                }
                if (result.contains("chat_number")) {
                    // 如果是多聊二维码，调用接口
                    mPresenter.getUserInfoByQrCode(getActivity(), result);
                } else if (TextHttpUtil.hasNetUrlHead(result)) {
                    // 网页链接，跳转到web界面
                    startActivity(new Intent(getActivity(), WebViewActivity.class)
                            .putExtra(WebViewActivity.INTENT_WEB_URL, result));
                } else {
                    // 都不是，直接展示结果
                    startActivity(new Intent(getActivity(), CaptureResultActivity.class)
                            .putExtra(CaptureResultActivity.INTENT_RESULT, result));
                }
            }
        }
    };

    /**
     * 分享名片点击
     *
     * @param message
     * @param userId
     */
    @Override
    public void shareUserOnClick(EMMessage message, int userId) {
        mPresenter.getUserInfo(getActivity(), userId, 1, true);
    }

    /**
     * 地理位置点击
     *
     * @param message
     * @param lat
     * @param lng
     */
    @Override
    public void locationOnClick(EMMessage message, double lat, double lng) {
        startActivity(new Intent(getActivity(), ChatMapActivity.class)
                .putExtra(ChatMapActivity.INTENT_LOCATION_LAT, lat)
                .putExtra(ChatMapActivity.INTENT_LOCATION_LNG, lng));
    }

    /**
     * 官方菜单消息点击
     *
     * @param id
     */
    @Override
    public void assistantOnClick(int id) {
        mPresenter.getChatAssistantMessage(getActivity(), "reply", id);
    }

    /**
     * 文本框里面电话点击
     *
     * @param phone
     */
    @Override
    public void callPhoneOnClick(String phone) {
        callPhone = phone;
        registerCallPhonePermission();
    }

    /**
     * 获取权限
     */
    private void registerCallPhonePermission() {
        premisionTag = 3;
        PermissionGen.with(this)
                .addRequestCode(Common.BASIC_PERMISSION_REQUEST_CODE)
                .permissions(Manifest.permission.CALL_PHONE)
                .request();
    }

    /**
     * 下载聊天图片
     */
    private void downLoadChatImg(EMMessage message, int id) {
        try {
            showLoading();
            String uri = null;
            if (message.getType() == EMMessage.Type.CUSTOM) {
                EMCustomMessageBody body = (EMCustomMessageBody) message.getBody();
                if (body.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)) {
                    String path = message.getStringAttribute(ChatConstant.EXTRA_IMAGE_PATH);
                    uri = path;
                }
            }
            if (EmptyUtils.isEmpty(uri)) {
                showError("图片地址已损坏");
                return;
            }
            ArrayList<EMMessage> emMessages = new ArrayList<>();
            emMessages.add(message);
            DownLoadUtil.downLoadImg(emMessages, new DownLoadUtil.OnDownLoadListener() {
                @Override
                public void success(String path) {
                    hideLoading();
                    mPresenter.upLoadImg(getActivity(), path, id);
                }

                @Override
                public void fail() {
                    hideLoading();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            showError("收藏失败:" + e.getMessage());
        }
    }

    /**
     * 发送收藏
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sendCollect(ChatCollectEvent event) {
        if (isDelete()) {
            if (!isService()) {
                ChatUtil.getInstance().insertDeleteMessage(conversation, username, receiveId,
                        EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName, messageStatusCallback);
                chatMsgListview.add();
                return;
            }
        }
        if (EmptyUtils.isEmpty(event.getImg())) {
            ChatUtil.getInstance().sendTxtMessage(event.getContent(), username, chatType, receiveId, EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName,
                    messageStatusCallback);
            chatMsgListview.add();
        } else {
            ChatUtil.getInstance().sendImgMessage(getActivity(), event.getImg(), username, chatType, receiveId, EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName,
                    messageStatusCallback);
            chatMsgListview.add();
        }
        if (EmptyUtils.isNotEmpty(event.getRemark())) {
            ChatUtil.getInstance().sendTxtMessage(event.getRemark(), username, chatType, receiveId, EmptyUtils.isEmpty(receiveRemarkName) ? receiveName : receiveRemarkName,
                    messageStatusCallback);
            chatMsgListview.add();
        }
    }

    /**
     * 备注名修改成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void remarkUpdateSuccess(UserRemarkEvent event) {
        hxUserInfoBean.setRemarks_name(event.getBean().getRemarks_name());
        receiveRemarkName = event.getBean().getRemarks_name();
        tvTitle.setText(event.getBean().getRemarks_name());
    }

    /**
     * 收到删除好友通知，判断是否是当前好友
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateDeleteState(ChatFriendDeleteEvent event) {
        if (userInfoBean == null) {
            return;
        }
        if (event.getId() == getMember_id()) {
            userInfoBean.setIs_del(1);
        }
    }

    /**
     * 收到添加好友通知，判断是否是当前好友
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateAddState(AddFriendEvent event) {
        if (userInfoBean == null) {
            return;
        }
        if (event.getId() == getMember_id()) {
            userInfoBean.setIs_del(0);
        }
    }

    // pragma mark
    private boolean isService() {
        return (userInfoBean != null && userInfoBean.isService());
    }

    private boolean isDelete() {
        return (userInfoBean != null && userInfoBean.isDel());
    }

    private boolean isAssistant() {
        return (userInfoBean != null && userInfoBean.isAssistant());
    }

    private int getMember_id() {
        return (userInfoBean != null ? userInfoBean.getMember_id() : 0);
    }

    @Override
    public void groupRefresh(String groupHXID) {
        tvTitle.post(new Runnable() {
            @Override
            public void run() {
                if (groupHXID != null&&userInfoBean!=null && userInfoBean.groupInfoBean!=null&&groupHXID.equals(userInfoBean.groupInfoBean.getHx_groupid())) {
                    ChatFragment.this.onResume();
                }
            }
        });

    }

    @Override
    public void groupDestroyed(String groupID) {
        tvTitle.post(new Runnable() {
            @Override
            public void run() {
                if (groupID != null&&userInfoBean!=null && userInfoBean.groupInfoBean!=null&&groupID.equals(userInfoBean.groupInfoBean.getHx_groupid())) {
                    ivTitleRight.setVisibility(View.GONE);
                    tvTitleRight.setVisibility(View.GONE);
                    ChatFragment.this.onResume();
                }
            }
        });

    }

    @Override
    public void groupMemberRemove(String groupID, String hxID) {
        tvTitle.post(new Runnable() {
            @Override
            public void run() {
                if (groupID != null&&userInfoBean!=null && userInfoBean.groupInfoBean!=null&&groupID.equals(userInfoBean.groupInfoBean.getHx_groupid())
                        && hxID != null && hxID.equals(UserInfoUtil.getUserXHId())) {
                    ivTitleRight.setVisibility(View.GONE);
                    tvTitleRight.setVisibility(View.GONE);
                    ChatFragment.this.onResume();
                    mPresenter.getGroupInfo(getActivity(), String.valueOf(receiveId));
                }
            }
        });

    }
}
